<template>
  <div v-if="!hasPermission('role:manage')" style="text-align: center; padding: 50px;">
    <a-result
      status="403"
      title="403"
      sub-title="抱歉，您没有权限访问权限管理页面。"
    >
      <template #extra>
        <a-button type="primary" @click="goToHome">返回首页</a-button>
      </template>
    </a-result>
  </div>
  
  <div v-else style="height: 100vh; width: 100wh; overflow-x: hidden; overflow-y: hidden;" @wheel.prevent>
    <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
      <a-input-search
        v-model:value="searchPermissionName"
        placeholder="请输入权限名称搜索"
        style="width: 200px; margin-right: 8px"
        @search="onSearch"
        @change="onSearchChange"
      />
      <a-button 
        v-permission="'role:manage'" 
        type="primary" 
        @click="showModal"
      >
        添加权限
      </a-button>
    </div>

    <a-modal v-model:open="open" title="添加权限" @ok="handleOk" @cancel="resetForm">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="权限名称" name="permissionName">
          <a-input v-model:value="formState.permissionName" placeholder="请输入权限名称" />
        </a-form-item>
        <a-form-item label="权限编码" name="permissionCode">
          <a-input v-model:value="formState.permissionCode" placeholder="请输入权限编码（如：user:manage）" />
        </a-form-item>
        <a-form-item label="权限描述" name="description">
          <a-textarea v-model:value="formState.description" placeholder="请输入权限描述" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-table 
      bordered
      :data-source="dataSource"
      :columns="columns"
      :loading="loading"
      :pagination="false"
      row-key="id"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="['permissionName', 'permissionCode', 'description'].includes(column.dataIndex)">
          <div class="editable-cell">
            <div v-if="editableData[record.id]" class="editable-cell-input-wrapper">
              <a-input 
                v-if="column.dataIndex === 'permissionName' || column.dataIndex === 'permissionCode'"
                v-model:value="editableData[record.id][column.dataIndex]" 
                @pressEnter="save(record.id)" 
              />
              <a-textarea 
                v-else-if="column.dataIndex === 'description'"
                v-model:value="editableData[record.id][column.dataIndex]" 
                @pressEnter="save(record.id)"
                :rows="2"
              />
              <check-outlined class="editable-cell-icon-check" @click="save(record.id)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              <span>{{ text || ' ' }}</span>
              <edit-outlined v-permission="'role:manage'" class="editable-cell-icon" @click="edit(record.id)" />
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createdAt'">
          {{ formatDate(text) }}
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a-button 
              v-permission="'role:manage'" 
              type="link" 
              size="small" 
              @click="edit(record.id)"
              style="margin-right: 8px"
            >
              编辑
            </a-button>
            <a-popconfirm
              v-permission="'role:manage'"
              v-if="dataSource.length"
              title="确定要删除该权限吗？"
              @confirm="onDelete(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>
    
    <div style="margin-top: 16px; text-align: right;">
      <a-pagination 
        v-model:current="current"
        show-quick-jumper
        :page-size-options="['5', '10', '20']"
        :total="total"
        @change="onChange"
        :page-size="pageSize"
        show-size-changer
      />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue'
import { permissionAPI } from '@/api/permission'
import { useRouter } from 'vue-router'
import PermissionUtil from '@/utils/permission'

// 路由
const router = useRouter()

// 权限检查（统一走工具，内置超级管理员放行）
const hasPermission = (permission) => PermissionUtil.hasPermission(permission)

const goToHome = () => {
  router.push('/')
}

// 搜索功能
const searchPermissionName = ref('')
const originalDataSource = ref([])

// 分页
const current = ref(1)
const total = ref(0)
// 每页显示多少条
const pageSize = ref(7)
const loading = ref(false)

// 表单配置
const formRef = ref()
const labelCol = { span: 6 }
const wrapperCol = { span: 16 }
const open = ref(false)

const formState = reactive({
  permissionName: '',
  permissionCode: '',
  description: ''
})

const rules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '权限编码长度应在2-50个字符之间', trigger: 'blur' },
    { pattern: /^[a-z:]+$/, message: '权限编码只能包含小写字母和冒号', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '权限描述不能超过255个字符', trigger: 'blur' }
  ]
}

const editableData = reactive({})

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '权限名称',
    dataIndex: 'permissionName'
  },
  {
    title: '权限编码',
    dataIndex: 'permissionCode'
  },
  {
    title: '权限描述',
    dataIndex: 'description',
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 150
  }
]

const dataSource = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 初始化数据
const initData = async () => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有查询权限')
    return
  }
  
  loading.value = true
  try {
    const response = await permissionAPI.getAllPermissions()
    if (response.data.success) {
      originalDataSource.value = Array.isArray(response.data.data) ? response.data.data : []
      total.value = originalDataSource.value.length
      const start = (current.value - 1) * pageSize.value
      const end = start + pageSize.value
      dataSource.value = originalDataSource.value.slice(start, end)
    } else {
      message.error('获取权限列表失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const onSearch = () => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有搜索权限')
    return
  }
  
  if (!searchPermissionName.value) {
    dataSource.value = originalDataSource.value
    return
  }
  
  dataSource.value = originalDataSource.value.filter(item => 
    item.permissionName.toLowerCase().includes(searchPermissionName.value.toLowerCase())
  )
}

const onSearchChange = () => {
  if (!searchPermissionName.value) {
    dataSource.value = originalDataSource.value
  }
}

// 分页
const onChange = (page, size) => {
  current.value = page
  pageSize.value = size
  const start = (current.value - 1) * pageSize.value
  const end = start + pageSize.value
  dataSource.value = originalDataSource.value.slice(start, end)
}

// 模态框
const showModal = () => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有创建权限权限')
    return
  }
  open.value = true
}

const resetForm = () => {
  formRef.value?.resetFields()
}

const handleOk = () => {
  formRef.value?.validate().then(async () => {
    try {
      const permissionData = {
        permissionName: formState.permissionName,
        permissionCode: formState.permissionCode,
        description: formState.description
      }
      
      const response = await permissionAPI.createPermission(permissionData)
      if (response.data.success) {
        message.success('权限创建成功')
        open.value = false
        resetForm()
        initData()
      } else {
        message.error(response.data.message || '创建失败')
      }
    } catch (error) {
      message.error(error.response?.data?.message || '创建失败')
    }
  }).catch(() => {
    message.error('请检查表单输入')
  })
}

// 编辑功能
const edit = (id) => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有编辑权限')
    return
  }
  editableData[id] = cloneDeep(dataSource.value.find(item => id === item.id))
}

const save = async (id) => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有更新权限')
    return
  }
  
  const editData = editableData[id]
  if (!editData) return
  
  try {
    const response = await permissionAPI.updatePermission(editData)
    if (response.data.success) {
      Object.assign(dataSource.value.find(item => id === item.id), editableData[id])
      delete editableData[id]
      message.success('更新成功')
    } else {
      message.error('更新失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '更新失败')
  }
}

// 删除功能
const onDelete = async (id) => {
  if (!hasPermission('role:manage')) {
    message.warning('您没有删除权限')
    return
  }
  
  try {
    const response = await permissionAPI.deletePermission(id)
    if (response.data.success) {
      dataSource.value = dataSource.value.filter(item => item.id !== id)
      originalDataSource.value = originalDataSource.value.filter(item => item.id !== id)
      message.success('删除成功')
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '删除失败')
  }
}



onMounted(() => {
  initData()
})
</script>

<style scoped>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  margin-top: 4px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>